﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.Common;

using Bpms.Data;
using Bpms.Entity;
using Bpms.Log;
using Bpms.Common;

namespace Bpms.Data.SqlServer
{
    public partial class DataProvider : IDataProvider
    {
        #region Private

        // 当前文件对应的逻辑类名，用于写日志
        string roleClassName = "Bpms.Data.SqlServer.Role";

        /// <summary>
        /// 绑定数据到角色实体
        /// </summary>
        /// <param name="idr">idatareader</param>
        /// <returns>IList<RoleInfo>对象</returns>
        IList<RoleInfo> GetDataBindedRole(IDataReader idr)
        {
            IList<RoleInfo> roleList = new List<RoleInfo>();

            while (idr.Read())
            {
                RoleInfo role = new RoleInfo();

                role.RoleID = (int)idr["role_id"];                          // 标识ID（角色ID）
                role.Name = idr["name"].ToString();                         // 角色名称
                role.Privilege = (long)idr["privilege"];                    // 权限
                role.ExtendPrivilege = (long)idr["extend_privilege"];       // 权限扩展
                role.Remark = idr["remark"].ToString();                     // 备注
                role.IsDelete = Convert.ToBoolean(idr["is_delete"]);                     // 是否删除（0：否，1：是）

                roleList.Add(role);
            }

            return roleList;
        }

        /// <summary>
        /// 根据sql语句返回角色信息
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns>角色对象</returns>
        RoleInfo GetRoleBySQL(string sql)
        {
            IList<RoleInfo> roleList = GetRoleListBySQL(sql);

            if (roleList.Count > 0)
            {
                return roleList[0];
            }
            else
            {
                return null;
            }
        }

        /// <summary>
        /// 根据sql语句返回角色列表
        /// </summary>
        /// <param name="sql">sql语句</param>
        /// <returns> IList<RoleInfo>对象</returns>
        IList<RoleInfo> GetRoleListBySQL(string sql)
        {
            IList<RoleInfo> roleList = new List<RoleInfo>();

            using (IDataReader idr = DbHelper.ExecuteReader(CommandType.Text, sql) as IDataReader)
            {
                try
                {
                    roleList = GetDataBindedRole(idr);
                }
                catch (Exception e)
                {
                    log.WriteLog(this.roleClassName + "：获取绑定的角色信息时出现异常", e);
                }
                finally
                {
                    if (idr != null)
                    {
                        idr.Close();
                    }
                }
            }

            return roleList;
        }

        #endregion

        /// <summary>
        /// 添加角色
        /// </summary>
        /// <param name="role">角色实体对象</param>
        /// <returns>-1：存在相同的记录（角色名称相同），0：添加失败，1：添加成功</returns>
        public bool InsertRole(RoleInfo role)
        {
            return true;
        }

        /// <summary>
        /// 修改角色
        /// </summary>
        /// <param name="role">角色实体对象</param>
        /// <returns>-1：存在相同的记录（角色名称相同），0：添加失败，1：添加成功</returns>
        public bool UpdateRole(RoleInfo role)
        {
            return true;
        }

        /// <summary>
        /// 删除角色
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns>删除是否成功（true：删除成功，false：删除失败）</returns>
        public bool DeleteRole(int roleId)
        {
            return true;
        }

        /// <summary>
        /// 判断角色名称是否存在
        /// </summary>
        /// <param name="role">角色对象</param>
        /// <param name="type">操作类别（添加或修改）</param>
        /// <returns>角色名称是否存在（true：已存在，false：不存在）</returns>
        public bool RoleExists(RoleInfo role, OperateType type)
        {
            return true;
        }

        /// <summary>
        /// 得到角色对象
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns>角色对象</returns>
        public RoleInfo GetRole(int roleId)
        {
            return null;
        }

        /// <summary>
        /// 得到角色列表
        /// </summary>
        /// <param name="pageId">当前页ID</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="condition">提取的条件</param>
        /// <returns>角色列表</returns>
        public IList<RoleInfo> GetRoles(int pageId, int pageSize, string condition)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(" SELECT TOP {0} role_id, [name], privilege, extend_privilege, remark, is_delete ");
            sbSql.Append(" FROM bp_role ");
            sbSql.Append(" WHERE {2} AND is_delete = 0 role_id NOT IN ");
            sbSql.Append(" ( ");
            sbSql.Append("      SELECT TOP {1} role_id FROM bp_role ");
            sbSql.Append("       WHERE {2} AND is_delete = 0 ");
            sbSql.Append("       ORDER BY role_id DESC ");
            sbSql.Append(" ) ");
            sbSql.Append(" ORDER BY role_id DESC ");

            string sql = sbSql.ToString();
            sbSql.Remove(0, sbSql.Length);
            sbSql.AppendFormat(sql, pageSize, pageSize * (pageId - 1), condition);

            return GetRoleListBySQL(sbSql.ToString());
        }

        /// <summary>
        /// 得到角色列表
        /// </summary>
        /// <param name="condition">提取的条件</param>
        /// <returns>角色列表</returns>
        public IList<RoleInfo> GetRoles(string condition)
        {
            StringBuilder sbSql = new StringBuilder();

            sbSql.Append(" SELECT  role_id, [name], privilege, extend_privilege, remark, is_delete FROM bp_role ");
            sbSql.Append(" WHERE is_delete = 0 ");
            if (condition.Trim().Length != 0)
            {
                sbSql.Append(" AND ").Append(condition);
            }
            else
            {
                sbSql.Append(" AND 1=1 ");
            }

            sbSql.Append(" ORDER BY role_id ASC ");

            return GetRoleListBySQL(sbSql.ToString());
        }

        /// <summary>
        /// 根据角色ID得到角色名称
        /// </summary>
        /// <param name="roleId">角色ID</param>
        /// <returns>角色名称</returns>
        public string GetRoleName(int roleId)
        {
            StringBuilder sbSql = new StringBuilder();
            sbSql.Append(" SELECT [name] FROM bp_role WHERE [role_id] = @role_id ");

            DbParameter[] parms = 
            { 
                DbHelper.MakeInParam("@role_id", (DbType)SqlDbType.Int, 4, roleId) 
            };
            object roleName = null;
            try
            {
                roleName = DbHelper.ExecuteScalar(CommandType.Text, sbSql.ToString(), parms).ToString() ?? "";
            }
            catch (Exception e)
            {
                log.WriteLog(this.userClassName + "：根据角色的ID，得到角色名称时出现异常", e);
            }

            return roleName.ToString();
        }
    }
}
